/**
 * JAVACC DEMO 1.0
 */
package com.apache.portal.common.template;

import com.apache.portal.common.template.method.*;
import com.apache.portal.thread.FileOperateUtil;
import com.apache.tools.StrUtil;
import com.apache.uct.common.ToolsUtil;
import freemarker.template.Configuration;
import freemarker.template.Template;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.*;
import java.util.Locale;
import java.util.Map;

/**
 * description:  模板操作辅助类
 *
 * @author Hou Dayu 创建时间：2016-7-8
 */
public class FreemarkerHelper {

    private Logger log = LoggerFactory.getLogger(FreemarkerHelper.class);

    private static FreemarkerHelper helper;

    private Configuration freemarker_cfg = null;

    private Configuration freemarker_cfg_priex = null;

    private Configuration freemarker_cfg_resources = null;

    private FreemarkerHelper() {
    }

    public static FreemarkerHelper instance() {
        if (null == helper) {
            helper = new FreemarkerHelper();
        }
        return helper;
    }
    /**
     * 读取的WEB-INF目录下模板
     */
    public String getTemplateStr(Map mapData, String... param) throws Exception {
        Template template = null;
        String templateName = param[0];
        String ifFontDesk = String.valueOf(mapData.get("ifFontDesk"));
        if (param.length > 1) {
            ifFontDesk = StrUtil.doNull(ifFontDesk, param[1]);
        }
        if (StrUtil.isNull(ifFontDesk)) {
            template = getFreeMarkerCFG().getTemplate(templateName);
        } else {
            template = getFreeMarkerCFGPrefix().getTemplate(templateName);
        }
        mapData.remove("ifFontDesk");
        template.setEncoding("UTF-8");

        StringWriter stream = new StringWriter();
        template.process(mapData, stream);
        String sndRtn = stream.toString();//FreeMarkerTemplateUtils.processTemplateIntoString(template, mapData);
        return sndRtn;
    }

    /**
     * 读取的resources目录下模板
     */
    public String getTemplateResourcesStr(Map mapData, String... param) throws Exception {
        String templateName = param[0];
        log.info("读取[resources]下的模板："+templateName);
        Template template = getFreeMarkerResourcesTempalte().getTemplate(templateName);
        mapData.remove("ifFontDesk");
        template.setEncoding("UTF-8");
        StringWriter stream = new StringWriter();
        template.process(mapData, stream);
        String sndRtn = stream.toString();//FreeMarkerTemplateUtils.processTemplateIntoString(template, mapData);
        return sndRtn;
    }

    /**
     * 生成静态页面的方法
     *
     * @param data 装载数据的结果集
     */
    public boolean createHtml(String ftlPath, Map<String, Object> data, String... param) {
        String htmlPath = param[0];
        if (ToolsUtil.isNull(ftlPath) || ToolsUtil.isNull(htmlPath))
            return false;
        Writer out = null;
        htmlPath = FileOperateUtil.getFormatFilePath(htmlPath);
        String hPath = htmlPath.substring(0, htmlPath.lastIndexOf("/") + 1);
        try {
            //指定模板路径//
            Template template = null;
            String ifFontDesk = String.valueOf(data.get("ifFontDesk"));
            if (param.length > 1) {
                ifFontDesk = StrUtil.doNull(ifFontDesk, param[1]);
            }
            if (StrUtil.isNull(ifFontDesk)) {
                template = getFreeMarkerCFG().getTemplate(ftlPath);
            } else {
                template = getFreeMarkerCFGPrefix().getTemplate(ftlPath);
            }
            data.remove("ifFontDesk");
            if (template == null)
                return false;
            FileOperateUtil.newCreateFolder(hPath);
            File htmlFile = new File(htmlPath);
            out = new BufferedWriter(
                    new OutputStreamWriter(new FileOutputStream(htmlFile), "UTF-8"));
            template.process(data, out); //处理模板
            out.flush();
        } catch (Exception e) {
            e.printStackTrace();
            log.error(e.getMessage());
            return false;
        } finally {
            try {
                if (out != null)
                    out.close();
            } catch (Exception e) {
                log.error(e.getMessage());
            }
        }
        return true;
    }

    /**
     * 生成静态页面的方法
     *
     * @param data     装载数据的结果集
     */
    //	public void viewPage(String ftlPath, Map<String, Object> data, HttpServletResponse response) {
    //		PrintWriter out = null;
    //		try {
    //			out = response.getWriter();
    //			//指定模板路径//
    //			Template template = getFreeMarkerCFG().getTemplate(ftlPath);
    //			if (template == null)
    //				return;
    //			response.setCharacterEncoding("UTF-8");
    //			template.setEncoding("UTF-8");
    //			template.process(data, out); //处理模板
    //		} catch (Exception e) {
    //			e.printStackTrace();
    //		} finally {
    //			try {
    //				//if (out != null)
    //				//out.close();
    //			} catch (Exception e) {
    //				log.error(e.getMessage());
    //			}
    //		}
    //	}

    /**
     * 获取freemarker的配置. freemarker本身支持classpath,目录和从ServletContext获取.
     */
    private Configuration getFreeMarkerCFG() {
        if (null == freemarker_cfg) {
            File templateFile = new File(
                    ToolsUtil.getClassLoaderPath().replaceAll("WEB-INF/classes/", "WEB-INF/")
                            + "template/");
            //
            freemarker_cfg = new Configuration();
            try {
                freemarker_cfg.setDirectoryForTemplateLoading(templateFile);
                freemarker_cfg.setEncoding(Locale.CHINA, "UTF-8");
            } catch (IOException e) {
                log.error("Get tempalte error", e);
            }
            freemarker_cfg.setSharedVariable("timeStr", new FormatDateMethod());
            freemarker_cfg.setSharedVariable("priceStr", new FormatPriceMethod());
            freemarker_cfg.setSharedVariable("subString", new SubStringMethod());
            freemarker_cfg.setSharedVariable("str", new StringNullMethod());
            freemarker_cfg.setSharedVariable("statusText", new WbdInfoStatusMethod());
        }
        return freemarker_cfg;
    }

    private Configuration getFreeMarkerCFGPrefix() {
        if (null == freemarker_cfg_priex) {
            File templateFile = new File(
                    ToolsUtil.getClassLoaderPath().replaceAll("WEB-INF/classes/", "wcm/"));
            freemarker_cfg_priex = new Configuration();
            try {
                freemarker_cfg_priex.setDirectoryForTemplateLoading(templateFile);
                freemarker_cfg_priex.setEncoding(Locale.CHINA, "UTF-8");
            } catch (IOException e) {
                log.error("Get tempalte error", e);
            }
            freemarker_cfg_priex.setSharedVariable("timeStr", new FormatDateMethod());
            freemarker_cfg_priex.setSharedVariable("priceStr", new FormatPriceMethod());
            freemarker_cfg_priex.setSharedVariable("subString", new SubStringMethod());
            freemarker_cfg_priex.setSharedVariable("str", new StringNullMethod());
            freemarker_cfg_priex.setSharedVariable("statusText", new WbdInfoStatusMethod());
        }
        return freemarker_cfg_priex;
    }

    /**
     * 获取配置在Resources中的tempalte模板配置对象
     * @return
     */
    private Configuration getFreeMarkerResourcesTempalte() {
        if (null == freemarker_cfg_resources) {
            freemarker_cfg_resources  = new Configuration();
            freemarker_cfg_resources.setClassForTemplateLoading(this.getClass(),"/templates");
            freemarker_cfg_resources.setEncoding(Locale.CHINA, "UTF-8");
            freemarker_cfg_resources.setSharedVariable("timeStr", new FormatDateMethod());
            freemarker_cfg_resources.setSharedVariable("priceStr", new FormatPriceMethod());
            freemarker_cfg_resources.setSharedVariable("subString", new SubStringMethod());
            freemarker_cfg_resources.setSharedVariable("str", new StringNullMethod());
            freemarker_cfg_resources.setSharedVariable("statusText", new WbdInfoStatusMethod());
        }
        return freemarker_cfg_resources;
    }
}
